const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🔐 用户权限管理')
  
  try {
    const { OPENID } = cloud.getWXContext()
    const { action, targetOpenid, permissions, roleId } = event
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 检查当前用户是否有管理权限
    const hasAdminPermission = await checkAdminPermission(OPENID)
    if (!hasAdminPermission) {
      return {
        success: false,
        error: '您没有权限执行此操作'
      }
    }
    
    switch (action) {
      case 'getUserPermissions':
        return await getUserPermissions(targetOpenid)
      case 'setUserPermissions':
        return await setUserPermissions(targetOpenid, permissions)
      case 'setUserRole':
        return await setUserRole(targetOpenid, roleId)
      case 'getAllUsers':
        return await getAllUsers()
      case 'getAllRoles':
        return await getAllRoles()
      case 'createRole':
        return await createRole(event.roleName, event.rolePermissions, event.roleDescription)
      case 'updateRole':
        return await updateRole(roleId, event.roleName, event.rolePermissions, event.roleDescription)
      case 'deleteRole':
        return await deleteRole(roleId)
      default:
        return {
          success: false,
          error: '未知操作'
        }
    }
    
  } catch (error) {
    console.error('❌ 权限管理操作失败:', error)
    return {
      success: false,
      error: error.message || '操作失败'
    }
  }
}

// 检查管理员权限
async function checkAdminPermission(openid) {
  try {
    const userResult = await db.collection('user_permissions')
      .where({ openid: openid })
      .get()
    
    if (userResult.data.length === 0) {
      // 如果是第一个用户，自动设为超级管理员
      const allUsersResult = await db.collection('user_permissions').count()
      if (allUsersResult.total === 0) {
        await createSuperAdmin(openid)
        return true
      }
      return false
    }
    
    const userPermissions = userResult.data[0]
    return userPermissions.permissions.includes('admin') || userPermissions.permissions.includes('super_admin')
    
  } catch (error) {
    console.error('❌ 检查管理员权限失败:', error)
    return false
  }
}

// 创建超级管理员
async function createSuperAdmin(openid) {
  try {
    await db.collection('user_permissions').add({
      data: {
        openid: openid,
        permissions: ['super_admin', 'admin', 'user_management', 'audit_management', 'data_management'],
        role: 'super_admin',
        roleName: '超级管理员',
        createTime: new Date(),
        updateTime: new Date()
      }
    })
    console.log('✅ 创建超级管理员成功:', openid)
  } catch (error) {
    console.error('❌ 创建超级管理员失败:', error)
    throw error
  }
}

// 获取用户权限
async function getUserPermissions(targetOpenid) {
  try {
    const result = await db.collection('user_permissions')
      .where({ openid: targetOpenid })
      .get()
    
    if (result.data.length === 0) {
      return {
        success: true,
        data: {
          openid: targetOpenid,
          permissions: ['basic'],
          role: 'user',
          roleName: '普通用户'
        }
      }
    }
    
    return {
      success: true,
      data: result.data[0]
    }
    
  } catch (error) {
    console.error('❌ 获取用户权限失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 设置用户权限
async function setUserPermissions(targetOpenid, permissions) {
  try {
    const existingResult = await db.collection('user_permissions')
      .where({ openid: targetOpenid })
      .get()
    
    if (existingResult.data.length === 0) {
      // 创建新的权限记录
      await db.collection('user_permissions').add({
        data: {
          openid: targetOpenid,
          permissions: permissions,
          role: 'custom',
          roleName: '自定义权限',
          createTime: new Date(),
          updateTime: new Date()
        }
      })
    } else {
      // 更新现有权限记录
      await db.collection('user_permissions')
        .doc(existingResult.data[0]._id)
        .update({
          data: {
            permissions: permissions,
            updateTime: new Date()
          }
        })
    }
    
    return {
      success: true,
      message: '用户权限设置成功'
    }
    
  } catch (error) {
    console.error('❌ 设置用户权限失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 设置用户角色
async function setUserRole(targetOpenid, roleId) {
  try {
    // 获取角色信息
    const roleResult = await db.collection('user_roles')
      .doc(roleId)
      .get()
    
    if (!roleResult.data) {
      return {
        success: false,
        error: '角色不存在'
      }
    }
    
    const role = roleResult.data
    
    const existingResult = await db.collection('user_permissions')
      .where({ openid: targetOpenid })
      .get()
    
    if (existingResult.data.length === 0) {
      // 创建新的权限记录
      await db.collection('user_permissions').add({
        data: {
          openid: targetOpenid,
          permissions: role.permissions,
          role: role.roleKey,
          roleName: role.roleName,
          roleId: roleId,
          createTime: new Date(),
          updateTime: new Date()
        }
      })
    } else {
      // 更新现有权限记录
      await db.collection('user_permissions')
        .doc(existingResult.data[0]._id)
        .update({
          data: {
            permissions: role.permissions,
            role: role.roleKey,
            roleName: role.roleName,
            roleId: roleId,
            updateTime: new Date()
          }
        })
    }
    
    return {
      success: true,
      message: '用户角色设置成功'
    }
    
  } catch (error) {
    console.error('❌ 设置用户角色失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取所有用户
async function getAllUsers() {
  try {
    // 获取所有有权限记录的用户
    const permissionsResult = await db.collection('user_permissions')
      .orderBy('updateTime', 'desc')
      .get()
    
    // 获取用户基本信息
    const users = []
    for (const permission of permissionsResult.data) {
      try {
        const userResult = await db.collection('users')
          .where({ openid: permission.openid })
          .get()
        
        const userInfo = userResult.data.length > 0 ? userResult.data[0] : {}
        
        users.push({
          openid: permission.openid,
          permissions: permission.permissions,
          role: permission.role,
          roleName: permission.roleName,
          userInfo: {
            nickName: userInfo.nickName || '未知用户',
            avatarUrl: userInfo.avatarUrl || '',
            lastLoginTime: userInfo.lastLoginTime || null,
            loginCount: userInfo.loginCount || 0
          },
          updateTime: permission.updateTime
        })
      } catch (userError) {
        console.warn('⚠️ 获取用户信息失败:', permission.openid, userError)
        users.push({
          openid: permission.openid,
          permissions: permission.permissions,
          role: permission.role,
          roleName: permission.roleName,
          userInfo: {
            nickName: '未知用户',
            avatarUrl: '',
            lastLoginTime: null,
            loginCount: 0
          },
          updateTime: permission.updateTime
        })
      }
    }
    
    return {
      success: true,
      data: users
    }
    
  } catch (error) {
    console.error('❌ 获取所有用户失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 获取所有角色
async function getAllRoles() {
  try {
    const result = await db.collection('user_roles')
      .orderBy('createTime', 'asc')
      .get()
    
    return {
      success: true,
      data: result.data
    }
    
  } catch (error) {
    console.error('❌ 获取所有角色失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 创建角色
async function createRole(roleName, rolePermissions, roleDescription) {
  try {
    const roleKey = roleName.toLowerCase().replace(/\s+/g, '_')
    
    await db.collection('user_roles').add({
      data: {
        roleKey: roleKey,
        roleName: roleName,
        permissions: rolePermissions,
        description: roleDescription,
        createTime: new Date(),
        updateTime: new Date()
      }
    })
    
    return {
      success: true,
      message: '角色创建成功'
    }
    
  } catch (error) {
    console.error('❌ 创建角色失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 更新角色
async function updateRole(roleId, roleName, rolePermissions, roleDescription) {
  try {
    await db.collection('user_roles')
      .doc(roleId)
      .update({
        data: {
          roleName: roleName,
          permissions: rolePermissions,
          description: roleDescription,
          updateTime: new Date()
        }
      })
    
    return {
      success: true,
      message: '角色更新成功'
    }
    
  } catch (error) {
    console.error('❌ 更新角色失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 删除角色
async function deleteRole(roleId) {
  try {
    await db.collection('user_roles')
      .doc(roleId)
      .remove()
    
    return {
      success: true,
      message: '角色删除成功'
    }
    
  } catch (error) {
    console.error('❌ 删除角色失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}
